package com.strato.annotation.base.v1_0_0.handler;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;

import org.osgi.framework.Bundle;

import com.strato.annotation.base.v1_0_0.activator.Activator;
import com.strato.annotation.base.v1_0_0.lifecycle.ServiceLifeCycle;
import com.strato.annotation.base.v1_0_0.registry.AnnotationRegistry;
import com.strato.annotation.base.v1_0_0.registry.BootStateful;
import com.strato.annotation.base.v1_0_0.registry.BundleDescriptor;
import com.strato.annotation.base.v1_0_0.registry.ClassDescriptor;
import com.strato.base.osgi.v1_0_0.BundleUtil;

public abstract class AbstractAnnotationHandler implements AnnotationHandler,ServiceLifeCycle,BootStateful {

	@Override
	public void handleClass(Bundle bundle, Class<?> clazz, Annotation annotation) {
	}

	@Override
	public void handleField(Bundle bundle, Field field, Class<?> clazz, Annotation annotation) {
	}

	@Override
	public void handleMethod(Bundle bundle, Method method, Class<?> clazz, Annotation annotation) {
	}

	@Override
	public void handleMethodParameter(Bundle bundle, Method method, Parameter p, Class<?> clazz, Annotation annotation) {
	}

	@Override
	public void handleFieldOnInstantiate(Bundle bundle, Field field, Class<?> clazz, Object object, Annotation fieldAnnotation) {
	}

	@Override
	public void handleMethodRuntime(Bundle bundle, MethodInvocation invocation, Class<?> clazz, Annotation classAnnotation, Annotation methodAnnotation) {
	}

	@Override
	public void onDiscoverClass(Bundle bundle, Class<?> clazz, ClassDescriptor classDescriptor) {
	}

	@Override
	public void handleUnresolve(Bundle bundle,BundleDescriptor bundleDescriptor) {
	}

	@Override
	public void handleUnresolveClass(Bundle bundle, ClassDescriptor classDescriptor) {
	}

	private boolean ready=true;
	
	@Override
	public void init() {
		try{
			ready=false;
			List<AnnotationHandler> handlers=new ArrayList<AnnotationHandler>();
			handlers.add(this);
			List<BundleDescriptor> bds = AnnotationRegistry.getInstance().getBundleDescriptors();
			for(BundleDescriptor bd:bds){
				Bundle bundle = BundleUtil.getBundle(bd.getName(), Activator.getContext());
				if(bundle!=null&&bundle.getState()==Bundle.ACTIVE){
					AnnotationRegistry.getInstance().applyHandlers(bd, handlers);
				}
			}
		}finally{
			ready=true;
		}
	}

	@Override
	public boolean isReady() {
		return ready;
	}
	
	
}
